import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_controller.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_page_counter.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/activity/activity_detail_model.dart';
import 'package:pornhub_app/model/activity/super_activity_model.dart';

class ActivityPageController extends BaseRefreshController
    with BaseRefreshPageCounter {
  final _pageSize = 20;
  List<SuperActivityModel> activityList = List<SuperActivityModel>.of([]);

  RxString imgString = "".obs;

  ActivityDetailModel _detailModel = ActivityDetailModel.fromJson({});
  ActivityDetailModel get detailModel => _detailModel;
  @override
  Future<IndicatorResult> onRefresh() async {
    resetPage();
    var r = await Api.getActivityImages(1);
    if (r != null) {
      imgString.value = r.imageUrl ?? "";
    }
    List<SuperActivityModel>? resp =
        await Api.getActivityItems(page: page, pageSize: _pageSize);
    isLoadData = true;
    if (resp == null) {
      return IndicatorResult.fail;
    }
    incPage();
    _setList(resp);
    update();
    return IndicatorResult.success;
  }

  @override
  Future<IndicatorResult> onLoad() async {
    List<SuperActivityModel>? resp =
        await Api.getActivityItems(page: page, pageSize: _pageSize);
    isLoadData = true;

    if (resp == null) {
      return IndicatorResult.fail;
    }

    _addList(resp);
    update();
    if (resp.length < _pageSize) {
      return IndicatorResult.noMore;
    }
    incPage();

    return IndicatorResult.success;
  }

  void _setList(List<SuperActivityModel>? list) {
    activityList.clear();
    _addList(list);
  }

  void _addList(List<SuperActivityModel>? list) {
    if (null != list && list.isNotEmpty) {
      activityList.addAll(list);
      update();
    }
  }

  bool isLoadData = false;
  Future<void> getActivityDetailById(int activityId) async {
    try {
      var resp = await Api.getDetailByActivityId(activityId: activityId);
      isLoadData = true;
      if (resp != null) {
        _detailModel = resp;
      }
    } catch (e) {}
    update();
  }

  Future<bool?> joinByActivityId(int activityId) async {
    return await Api.joinByActivityId(activityId);
  }
}
